from django.shortcuts import render,redirect
from django.views import View
from django.urls import reverse
from django.http.response import JsonResponse,HttpResponse
from apps.goods.models import GoodsSKU
from django_redis import get_redis_connection
from utils.mixin import LoginRequiredMixin
# Create your views here.

#/cart/add
class CartAddView(View):
    """添加购物车"""
    def post(self,request):
        user = request.user
        if not user.is_authenticated:
            # 用户未登录
            return JsonResponse({'res': 0, 'errmsg': '请先登录'})

        #接收数据
        cart_id=request.POST.get("sku_id")
        count=request.POST.get("count")

        #校检数据
        if not all([cart_id,count]):
            return JsonResponse({"res":1,"errmsg":"数据不完整"})

        try:
            sku=GoodsSKU.objects.get(id=cart_id)
        except GoodsSKU.DoesNotExist:
            return JsonResponse({"res":2,"errmsg":"商品不存在"})

        # 校验添加的商品数量
        try:
            count = int(count)
        except Exception as e:
            # 数目出错
            return JsonResponse({'res': 3, 'errmsg': '商品数目出错'})

        if count>sku.stock:
            return JsonResponse({"res":4,"errmsg":"库存不足"})

        #业务逻辑:添加购物车
        conn=get_redis_connection("default")
        cart_key="cart_%d" % request.user.id
        cart_count=conn.hget(cart_key,cart_id)
        if cart_count:
            count+=int(cart_count)

        conn.hset(cart_key,cart_id,count)
        total_count=conn.hlen(cart_key)

        #应答
        return JsonResponse({"res":5,"errmsg":"添加成功","total_count":total_count})

class CartIndexView(LoginRequiredMixin,View):
    """购物车页面"""
    def get(self,request):
        #查询数据
        user=request.user
        conn=get_redis_connection("default")
        cart_key="cart_%d" % user.id
        cart_skus=conn.hgetall(cart_key)
        count=conn.hlen(cart_key)
        skus=[]
        for sku_id,sku_count in cart_skus.items():
            try:
                sku=GoodsSKU.objects.get(id=int(sku_id))
            except GoodsSKU.DoesNotExist:
                sku=None
            amount=sku.price*int(sku_count)
            skus.append({
                "good_sku":sku,
                "count":int(sku_count),
                "amount":amount
            })
        content={
            "skus":skus,
            "count":count
        }

        return render(request,"cart.html",content)

class CartUpdateView(View):
    """购物车更新"""
    def post(self,request):
        user = request.user
        if not user.is_authenticated:
            # 用户未登录
            return JsonResponse({'res': 0, 'errmsg': '请先登录'})

        # 接收数据
        cart_id = request.POST.get("sku_id")
        count = request.POST.get("count")

        # 校检数据
        if not all([cart_id, count]):
            return JsonResponse({"res": 1, "errmsg": "数据不完整"})

        try:
            sku = GoodsSKU.objects.get(id=cart_id)
        except GoodsSKU.DoesNotExist:
            return JsonResponse({"res": 2, "errmsg": "商品不存在"})

        # 校验添加的商品数量
        try:
            count = int(count)
        except Exception as e:
            # 数目出错
            return JsonResponse({'res': 3, 'errmsg': '商品数目出错'})

        if count > sku.stock:
            return JsonResponse({"res": 4, "errmsg": "库存不足"})

        # 业务逻辑:添加购物车
        conn = get_redis_connection("default")
        cart_key = "cart_%d" % request.user.id

        conn.hset(cart_key, cart_id, count)

        # 应答
        return JsonResponse({"res": 5, "errmsg": "更新成功"})

#/cart/del
class CartDeleteView(View):
    """"购物车删除"""
    def post(self,request):
        user = request.user
        if not user.is_authenticated:
            # 用户未登录
            return JsonResponse({'res': 0, 'errmsg': '请先登录'})

        #接收数据
        sku_id=request.POST.get("sku_id")

        #校检数据
        if not all(sku_id):
            return JsonResponse({
                "res":1,
                "errmsg":"数据不完整"
            })

        try:
            sku = GoodsSKU.objects.get(id=sku_id)
        except GoodsSKU.DoesNotExist:
            return JsonResponse({"res": 2, "errmsg": "商品不存在"})

        #删除购物车记录
        conn=get_redis_connection("default")
        cart_key = "cart_%d" % request.user.id
        count=conn.hget(cart_key,sku_id)
        if not count:
            return JsonResponse({
                "res":3,
                "errmsg":"没有此商品的记录"
            })
        conn.hdel(cart_key,sku_id)

        #响应应答
        return JsonResponse({
            "res": 4,
            "errmsg": "删除成功"
        })